import { parseTime } from '@/utils'
import { isEmpty } from 'lodash'

function defaultValueFactory(defaultValue) {
  return {
    $date$: function() {
      return parseTime(new Date(), '{y}-{m}-{d}')
    },
    $time$: function() {
      return parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    }
  }[defaultValue]
}

export function defaultValueParser(element) {
  const defaultValue = element.defaultValue
  const parser = defaultValueFactory(defaultValue)
  if (isEmpty(parser)) {
    return defaultValue
  }
  return defaultValue
}

export function scriptParser(scripts, data) {
  scripts = scripts || ''
  const vars = []
  const keys = Object.keys(data)
  keys.forEach(key => {
    const value = data[key]
    const sv = 'const ' + key + ' =' + value
    vars.push(sv)
  })
  const cVars = vars.join(';\n')
  const exec = cVars + ' (function () { return' + scripts + ' })'
  console.log('exec script ' + exec)
  try {
    // eslint-disable-next-line no-eval
    return eval(exec)()
  } catch (e) {
    console.log('Script ' + scripts + 'eval Error!')
    return false
  }
}

export function defaultValidator(element) {
  return {
    required: element.required,
    message: element.validMessage,
    trigger: element.trigger
  }
}
